package com.logos.musicframe.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.logos.musicframe.constant.RedisConstant;
import com.logos.musicframe.converter.SongPlayHistoryConverter;
import com.logos.musicframe.converter.SongsConverter;
import com.logos.musicframe.entity.SongPlayHistory;
import com.logos.musicframe.entity.Songs;
import com.logos.musicframe.mapper.SongPlayHistoryMapper;
import com.logos.musicframe.mapper.SongsLikedMapper;
import com.logos.musicframe.mapper.SongsMapper;
import com.logos.musicframe.resp.SongPlayHistoryResp;
import com.logos.musicframe.resp.SongsResp;
import com.logos.musicframe.service.SongPlayHistoryService;
import com.logos.musicframe.service.SongsLikedService;
import com.logos.musicframe.service.SongsService;
import com.logos.musicframe.utils.RedisUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * 播放历史(SongPlayHistory)表服务实现类
 *
 * @author logos
 * @since 2025-06-16 10:31:56
 */
@Service("songPlayHistoryService")
@Slf4j
public class SongPlayHistoryServiceImpl implements SongPlayHistoryService {
    @Resource
    private SongPlayHistoryMapper songPlayHistoryMapper;

    @Autowired
    private SongsMapper songsMapper;

    @Autowired
    private SongsLikedService songsLikedService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public SongPlayHistory queryById(Long id) {
        return this.songPlayHistoryMapper.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param songPlayHistory 筛选条件
     * @param pageRequest     分页对象
     * @return 查询结果
     */
    @Override
    public Page<SongPlayHistory> queryByPage(SongPlayHistory songPlayHistory, PageRequest pageRequest) {
        long total = this.songPlayHistoryMapper.count(songPlayHistory);
        return new PageImpl<>(this.songPlayHistoryMapper.queryAllByLimit(songPlayHistory, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param songPlayHistory 实例对象
     * @return 实例对象
     */
    @Override
    public SongPlayHistory insert(SongPlayHistory songPlayHistory) {
        this.songPlayHistoryMapper.insert(songPlayHistory);
        return songPlayHistory;
    }

    /**
     * 修改数据
     *
     * @param songPlayHistory 实例对象
     * @return 实例对象
     */
    @Override
    public SongPlayHistory update(SongPlayHistory songPlayHistory) {
        this.songPlayHistoryMapper.update(songPlayHistory);
        return this.queryById(songPlayHistory.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.songPlayHistoryMapper.deleteById(id) > 0;
    }

    /**
     * 查询用户历史播放记录
     *
     * @param userId
     * @return
     */
    @Override
    public List<SongPlayHistoryResp> queryByUser(Integer userId) {
        // 查看缓存中是否存在
        if (redisUtil.exist(RedisConstant.SONG_PLAY_HISTORY_USER + userId)) {
            List<SongPlayHistoryResp> songPlayHistoryRespList = JSONObject.parseArray(redisUtil.get(RedisConstant.SONG_PLAY_HISTORY_USER + userId), SongPlayHistoryResp.class);
            log.info("songPlayHistoryService.queryByUser.Cache.Hit:{}", songPlayHistoryRespList);
            return songPlayHistoryRespList;
        }
        SongPlayHistory songPlayHistory = new SongPlayHistory().setUserId(userId);
        Pageable pageable = PageRequest.of(0, 10);
        List<SongPlayHistory> songPlayHistoryList = songPlayHistoryMapper.queryAllByLimit(songPlayHistory, pageable);
        if (songPlayHistoryList == null || songPlayHistoryList.isEmpty()) {
            return null;
        }
        List<SongPlayHistoryResp> songPlayHistoryRespList = songPlayHistoryList.stream().map(SongPlayHistoryConverter.INSTANCE::convertEntityToResp).toList();
        // CompletableFuture 多线程优化
        List<SongPlayHistoryResp> songPlayHistoryRespListResult = songPlayHistoryRespList.stream().map(songPlayHistoryResp -> CompletableFuture.supplyAsync(() -> {
            Integer songId = songPlayHistoryResp.getSongId();
            Songs songs = songsMapper.queryById(songId);
            SongsResp songsResp = SongsConverter.INSTANCE.convertEntityToResp(songs);
            // 查询该歌曲是否被点赞
            boolean liked = songsLikedService.isLiked(userId, songId);
            songsResp.setIsLiked(liked);
            songPlayHistoryResp.setSongsResp(songsResp);
            return songPlayHistoryResp;
        })).toList().stream().map(CompletableFuture::join).toList();
        // 存入缓存
//        redisUtil.setNx(RedisConstant.SONG_PLAY_HISTORY_USER + userId, JSONObject.toJSONString(songPlayHistoryRespListResult), RedisConstant.EXPIRE_TIME_THREE_MINUTES);
        return songPlayHistoryRespListResult;
    }

    @Override
    public Boolean add(Integer userId, Integer songId) {
        // 查看是否有这条播放记录
        SongPlayHistory songPlayHistory = new SongPlayHistory().setUserId(userId).setSongId(songId);
        List<SongPlayHistory> songPlayHistoryList = songPlayHistoryMapper.queryByCondtion(songPlayHistory);
        // TODO 播放次数再说
        if (songPlayHistoryList != null && !songPlayHistoryList.isEmpty()) {
            // 存在这条记录，则更新播放时间
            songPlayHistory = songPlayHistoryList.get(0);
            songPlayHistory.setPlayTime(String.valueOf(System.currentTimeMillis()));
            return songPlayHistoryMapper.update(songPlayHistory) > 0;
        }else{
            songPlayHistory = new SongPlayHistory().setUserId(userId).setSongId(songId).setPlayTime(String.valueOf(System.currentTimeMillis()));
            return songPlayHistoryMapper.insert(songPlayHistory) > 0;
        }
    }
}
